<?php

    use app\data\model\About_link;
    use app\data\model\CompanyInfo;
    use app\data\model\CurriculumOrderRecord;
    use app\data\model\DataPUser;
    use app\data\model\DataRewardOrder;
    use app\data\model\DataUser;
    use app\data\model\FixItems;
    use app\data\model\LogUserCurrModel;
    use app\data\model\MarketCollageDetail;
    use app\data\model\MarketingReward;
    use app\data\model\RotationImg;
    use app\data\model\Severity;
	use app\data\model\ShopOrder;
	use app\data\model\SubjectKaoTopic;
use app\data\model\SubjectTopic;
    use app\data\service\UserAdminService;
    use app\data\service\UserTokenService;
    use think\exception\HttpResponseException;
    use think\facade\Session;
	use WeMini\Scheme;

	function dd($data , $die = false){
    allow_ajax();
    echo "<debug>";
    dump(json_decode(json_encode($data),1));
    echo "</debug>";
    if($die){die;}
}
/*
 * 允许跨域请求
 * */
function allow_ajax(){
    header('Access-Control-Allow-Origin:*');
    header('Access-Control-Allow-Methods:POST');
    header('Access-Control-Allow-Headers:x-requested-with,content-type');
}
function e($info, $data = '{-null-}', $res_code = 0, $code = 0): void
{
    if ($data === '{-null-}') $data = new stdClass();
    throw new HttpResponseException(json([
        'code' => $code, 'info' => $info, 'data' => $data, 'res_code' => $res_code
    ]));
}
/*
 * 是否是debug模式*/
function is_debug(){
    $debug = false;
    if(input('debug')){$debug = true;}
    return $debug;
}

/*
 * 给链接增加字段 url加参数
 * @param 数组 [ data1=>1 , data2=>2 ]*/
function url_add_param($url , $param){
    $url = trim($url,'&');
    $url = trim($url,'?');
    $domain = $url;$old_param = '';
    // 得到纯净的域名
    if(strpos($url , '?')){$domain_arr = explode('?',$url);}
    // 在后边拼接参数
    if(!empty($domain_arr)){
        $domain = $domain_arr[0];
        $old_param = $domain_arr[1];// 原链接数据字串
    }
    $old_param_arr = explode('&',$old_param);
    if(empty($old_param)){$old_param_arr = [];}
    $keys = array_keys($param);
    foreach($old_param_arr as $v){
        $arr = explode('=',$v);
        if(in_array($arr[0] , $keys)){continue;}
        $param[$arr[0]] = $arr[1];
        $keys = array_keys($param);
    }
    $url = $domain;
    foreach($param as $k=>$v){
        if(strpos($url , '?')){$url .= '&'.$k.'='.$v;}
        else{$url .= '?'.$k.'='.$v;}
    }
    return $url;
}
/*
 * 生成订单号
 * */
function getorderno($p = "")
{
    return $p . date("ymdHis") . str_pad(getMillisecond() % 1000, 4, "0", STR_PAD_LEFT) . random(4);
}
function getMillisecond()
{
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}
function random($len, $type = "number")
{
    $srcstr = "";
    if ($type == "number") {
        $srcstr = "1234567890";
    }
    if ($type == "string") {
        $srcstr = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    }
    mt_srand();
    $strs = "";
    for ($i = 0; $i < $len; $i++) {
        $strs .= $srcstr[mt_rand(0, strlen($srcstr) - 1)];
    }
    return $strs;
}
/*
 * 判断字符串是不是json格式
 * */
function is_json($string)
{
    if(empty($string)){return false;}
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}
/*
 * 值替换
 * @data 原数据 例 : ['a'=>'name','b'=>'tel']
 * @param 替换规则 例 : ['name'=>'名字','tel'=>'电话']
 * @return 返回数组 例 : ['a'=>'名字','b'=>'电话']*/
function arr_field_replace($arr , $param){
    $return = [];
    foreach($arr as $k=>$value){
        if(isset($param[$value])){
            $return[$k] = $param[$value];
        }else{
            $return[$k] = $value;
        }
    }
    return $return;
}
/*
 * 秒转时长
 * @seconds 秒数
 * @return 转化后的时分秒*/
function second2timestr($seconds){
    if ($seconds > 3600){
        $hours = intval($seconds/3600);
        $minutes = $seconds % 3600;
        $time = $hours.":".gmstrftime('%M:%S', $minutes);
    }else{
        $time = gmstrftime('%H:%M:%S', $seconds);
    }
    return $time;
}
/*
 * 生成二维码
 * */
if ( !function_exists('make_ewm') ) {
    function make_ewm($url = ""){
        require "./phpqrcode/phpqrcode.php";
        $size = 4;//图片大小
        $errorCorrectionLevel = "Q"; // 容错级别：L、M、Q、H
        $matrixPointSize = "8"; // 点的大小：1到10
        //实例化
        $qr = new \QRcode();
        //会清除缓冲区的内容，并将缓冲区关闭，但不会输出内容。
        ob_end_clean();
        //输出二维码
        $qr::png($url, false, $errorCorrectionLevel, $matrixPointSize);
    }
}


    //获取每个人的 订单数量
    function user_reward_order($user_id){
        $uid = $user_id;
        //订单数量 () curriculum_order_record 和 market_collage_detail表
        //订单状态 0待付款1已付款(待发货)2已完成3取消4待收货
        $cnt1 = CurriculumOrderRecord::where(['user_id'=>$uid])->where('status','<>',3)->count();
        //拼单状态 1 成功 0 失败
        $cnt2 = MarketCollageDetail::
            alias('a')
            ->LeftJoin('market_collage_order b','a.order_id = b.id')
            ->where(['a.user_id'=>$uid,'b.status'=>1])
            ->where('pin_status','<>',3)->count();
        $data['order_cnt'] = $cnt1+$cnt2;
        return $data;
    }
    //获取我的分销人员
    function my_reward_user_cnt($user_id){
        //我的一级分销人员
        $my_user_level1 = DataUser::
        // field('id,username,nickname,headimg,pay_total,create_at')
            field('*')
            ->where(['pid1'=>$user_id])->select()
        ->each(function($data){
            $uid = $data['id'];
            // $r = $this->user_reward_order($uid);
            // $data['order_cnt'] = $r['order_cnt'];
            // $data['person_cnt'] = $r['person_cnt'];
        })
            ->toArray();

        $set = MarketingReward::mk()->where('id','=',1)->find();
        // 分销模式 0关闭 1一级分销 2二级分销
        $fx_model = $set['fx_model'];
        //二级分销人员
        $my_user_level2 = [];
        if ($fx_model == 2){
            foreach($my_user_level1 as $v){
                $pid1 = $v['id'];
                $my_user_level2_data = DataUser::
                // field('id,username,nickname,headimg,pay_total,create_at')
                    field('*')
                    ->where(['pid1'=>$pid1])->select()
                    ->each(function($data){
                        $uid = $data['id'];
                        $r = user_reward_order($uid);
                        $data['order_cnt'] = $r['order_cnt'];
                        // $data['person_cnt'] = $r['person_cnt'];
                    })
                    ->toArray();
                $my_user_level2 = array_merge($my_user_level2,$my_user_level2_data);
            }
        }else{

        }
        $my_user_level1_cnt = count($my_user_level1);
        $my_user_level2_cnt = count($my_user_level2);
        $rt['my_user_level1'] = $my_user_level1;
        $rt['my_user_level1_cnt'] = $my_user_level1_cnt;
        $rt['my_user_level2'] = $my_user_level2;
        $rt['my_user_level2_cnt'] = $my_user_level2_cnt;
        return $rt;
    }

    /*
     * 计算金额
     */
    function computed_money($user_id,$money)
    {
        $rt = [];
        // 订单金额0 不返利
        if ($money <= 0) return $rt;
        // 获取用户数据
        $map = ['id' => $user_id, 'deleted' => 0];
        $user = DataUser::mk()->where($map)->find();
        if (empty($user)) throw new Exception('用户不存在');
        //非得
        $set = MarketingReward::mk()->where('id','=',1)->find();
        // 分销模式 0关闭 1一级分销 2二级分销
        $fx_model = $set['fx_model'];
        // 佣金类型 0百分比 1固定金额
        $yj_type = $set['yj_type'];
        //一级分销 百分比or固定金额
        $one_distribution = $set['one_distribution'];
        //二级分销 百分比or固定金额
        $two_distribution = $set['two_distribution'];
        $distribution = [$one_distribution,$two_distribution];
        $user_id = $user_id;

        for ($i=0;$i<$fx_model;$i++)
        {
            $user_data = DataUser::mk()->where([])->where('id','=',$user_id)->find()->toArray();
            $money_1 = 0;
            $user_id_1 = 0;
            if (!empty($user_data)){
                $user_id_1 = $user_data['pid1'];
                $user_id = $user_id_1;
                $num = $distribution[$i];
                if ($yj_type == 0){
                    $money_1 = floor(strval($num * $money / 100) * 100) / 100;
                }else if($yj_type == 1){
                    $money_1 = $num;
                }
            }
            $row['money'] = $money_1;
            $row['user_id'] = $user_id_1;
            $rt[]=$row;
        }

        return ($rt);
        return json_encode($rt);
    }

    /*
     * 记录分销订单表
     * user_id 人员
     * type 类型 0vip 1拼团线上课程 2拼团线下课程 3拼团实体书 4限时抢购 5线上课程 6线下课程 7实体书
     * money 金额
     */
    function insert_reward_order($user_id,$type,$money,$order_id,$vx_uuid)
    {
        // if (cache('insert_reward_order_vx_uuid')){
        //     if ($vx_uuid === cache('insert_reward_order_vx_uuid')){
        //         return;
        //     }
        // }else{
        //     cache('insert_reward_order_vx_uuid',$vx_uuid);
        // }
        //人员
        //类型
        //金额
        //一级分销人
        $pid1 = 0;
        //一级分销佣金
        $money1 = 0;
        //二级分销人
        $pid2 = 0;
        //二级分销佣金
        $money2 = 0;
        $rt = computed_money($user_id,$money);
        // return $rt;

        foreach($rt as $k=>$v){
            if ($k==0){
                $pid1 = $v['user_id'];
                $money1 = $v['money'];
                //user表中添加奖励金
                // rebate_total
                add_user_rebate_total($pid1,$money1);
                $User = DataUser::mk()->where(['id'=>$pid1])->find();
                $openid = $User['openid2'];
                $text = '恭喜，您获得了一笔新的分销佣金~';
                $data_options['touser'] = $openid;
                $data_options['template_id'] = 'RjipIAsvdb-AksrBrAvSrPYLnGz9kRmvqIZ2n4IaQtE';
                $data_options['data']['first']['value'] = $text;
                $data_options['data']['keyword1']['value'] = $money1;
                $data_options['data']['keyword2']['value'] = $money;
                $data_options['data']['keyword3']['value'] = date("Y-m-d H:i:s");
                $data_options['data']['remark']['value'] = '感谢你的使用，再接再厉哦！';
                sendfa($data_options);

            }else if($k==1){
                $pid2 = $v['user_id'];
                $money2 = $v['money'];
                add_user_rebate_total($pid2,$money2);
                $User = DataUser::mk()->where(['id'=>$pid2])->find();
                $openid = $User['openid2'];
                $text = '恭喜，您获得了一笔新的分销佣金~';
                $data_options['touser'] = $openid;
                $data_options['template_id'] = 'RjipIAsvdb-AksrBrAvSrPYLnGz9kRmvqIZ2n4IaQtE';
                $data_options['data']['first']['value'] = $text;
                $data_options['data']['keyword1']['value'] = $money2;
                $data_options['data']['keyword2']['value'] = $money;
                $data_options['data']['keyword3']['value'] = date("Y-m-d H:i:s");
                $data_options['data']['remark']['value'] = '感谢你的使用，再接再厉哦！';
                sendfa($data_options);
            }
        }
        $now_time = date("Y-m-d H:i:s");
        $data = [
            'user_id'=>$user_id,
            'type'=>$type,
            'order_id'=>$order_id,
            'money'=>$money,
            'pid1'=>$pid1,
            'money1'=>$money1,
            'pid2'=>$pid2,
            'money2'=>$money2,
            'status'=>2,
            'bk_datatime'=>$now_time,
        ];
        DataRewardOrder::mk()->insert($data);

        return $data;
    }
    //user表中添加奖励金
    function add_user_rebate_total($user_id,$money){
        //user表中添加奖励金
        // rebate_total
        $DataUser = DataUser::field('rebate_total')->where(['id'=>$user_id])->find();
        $old_rebate_total = $DataUser->rebate_total;
        $new_rebate_total = $old_rebate_total + $money;
        DataUser::where(['id'=>$user_id])->update(['rebate_total'=>$new_rebate_total]);
    }

    //user表中添加消费金额
    function add_user_pay_total($user_id,$money,$vx_uuid){
        // if (cache('add_user_pay_total_vx_uuid')){
        //     if ($vx_uuid === cache('add_user_pay_total_vx_uuid')){
        //         return;
        //     }
        // }else{
        //     cache('add_user_pay_total_vx_uuid',$vx_uuid);
        // }
        //user表中添加奖励金
        // rebate_total
        $DataUser = DataUser::field('pay_total')->where(['id'=>$user_id])->find();
        $old_pay_total = $DataUser->pay_total;
        $new_pay_total = $old_pay_total + $money;
        DataUser::where(['id'=>$user_id])->update(['pay_total'=>$new_pay_total]);
    }



/******本项目自用函数*******************************************************************************************************************/
/*
 * 生成VIP订单号
 * */
function getviporderno($p = ""){
    return $p . date("ymdHis") . str_pad(getMillisecond() % 1000, 4, "0", STR_PAD_LEFT) . random(4);
}
/*
 * 把题目格式化
 * @param $q 传来的一道题
 * @param $ans_list 我的答案*/
function make_web_ques($q , $ans_list = null){
    $ques_type_arr = [1=>'单选题',2=>'多选题',3=>'判断题'];
    $question = [];
    $question['questionType'] = $ques_type_arr[$q['ques_class']];// 题目类型
    $question['questionContent'] = $q['ques_content'];// 题干
    $question['questionOptions'] = [];// 选项
    $question['ques_score'] = $q['ques_score'];// 分数
    $arr = [1=>'A',2=>'B',3=>'C',4=>'D'];
    if($ans_list){
        if(is_json($ans_list)){
            $ans_list = json_decode($ans_list,1);
        }
    }
    /*
     * 处理我作答的答案*/
    $question['is_right'] = false;
    // 如果答案列表有这个题目
    if( isset($ans_list[$q['id']]) ){
        $question['my_ans'] = isset($ans_list[$q['id']])?$ans_list[$q['id']]:'';// 现在得到的是数字或者空
        if(2 == $q['ques_class']){
            // 多选
            $ques_result = explode(',',trim($q['ques_result'] , ','));// 拆成数组
            $question['ques_result'] = '';// 显示的答案默认空
            foreach($ques_result as $v){
                if(isset($arr[$v])){
                    $question['ques_result'] .= $arr[$v].',';
                }
            }
            $question['ques_result'] = trim($question['ques_result'],',');// 题目答案 A,B,C
            if($question['my_ans'] != ""){
                $a_l = explode(',',trim($question['my_ans'] , ','));// 我的答案拆数组
                $question['my_ans'] = "";
                foreach($a_l as $v){$question['my_ans'] .= $arr[$v].',';}
                $question['my_ans'] = trim($question['my_ans'],',');// 我的答案拼接回去
            }
        } else if(3 == $q['ques_class']){
            // 判断
            $question['ques_result'] = $q['ques_result'] == 0 ? '错误' : '正确';
            if($question['my_ans'] != ""){
                $question['my_ans'] = $question['my_ans'] == 0 ? '错误' : '正确';
            }
        }else{
            // 单选
            $question['ques_result'] = $arr[$q['ques_result']];
            $question['my_ans'] = isset($arr[$question['my_ans']]) ? $arr[$question['my_ans']] : '';
        }
        $question['is_right'] = $question['my_ans'] == $question['ques_result'];// 是否正确
    }
    /* 四个选项显示内容处理*/
    foreach($arr as $index=>$k){
        if($q['ques_result_'.$k] === null){continue;}
        $question['ques_class'] = $q['ques_class'];
        $question['topic_id'] = $q['id'];
        if(3 == $q['ques_class']){
            // 判断
            $question['questionOptions'][] = [
                'index_title'=>'·',// 前端显示的选项头 : ABCD·123等等
                'answer'=>strval($q['ques_result_'.$k]),// 本选项答案 - 显示
                'optionValue'=>strval(1-abs(1-$index)),// 本选项答案 - 值
            ];
        } else{
            // 单选 + 多选
            $question['questionOptions'][] = [
                'index_title'=>$k,
                'answer'=>strval($q['ques_result_'.$k]),
                'optionValue'=>strval($index),
            ];
        }
    }
    return $question;
}
/*
 * 传入试卷ID , 更新试卷的总分以及及格分等信息*/
function update_kao_pic_sorce($kaopic_id){
    $KaoTopic = SubjectKaoTopic::mk()->where('id',$kaopic_id)->find();// 试卷
    $subject_id = $KaoTopic['subject_id'];// 题目ID
    // 处理题目ID , 用题目ID查题目列表
    $ques_result_ = explode(',',$subject_id);
    $ques_result = [];
    foreach($ques_result_ as $v){
        if(!$v){continue;}
        $ques_result[] = $v;
    }
    $model = SubjectTopic::whereIn('id',$ques_result);
    $questions = $model->order('ques_class')->select();
    $update = [];
    $update['sum_score'] = 0;
    foreach($questions as $q){
        $update['sum_score'] += $q['ques_score'];
    }
    $update['pass_score'] = floor($update['sum_score'] * $KaoTopic['pass_billie']) / 100;// 及格分
    SubjectKaoTopic::mk()->where('id',$kaopic_id)->update($update);
}
/*
 * 计算考试成绩*/
function calc_exam_score($ans_list = null){
    if(empty($ans_list)){return 0;}
    if(is_string($ans_list)){
        $ans_list = json_decode($ans_list,1);
    }
    $subject_id = array_keys($ans_list);
    $subjects = SubjectTopic::mk()->whereIn('id',$subject_id)->field('id,ques_score,ques_result,ques_class')->select();
    $sorce_sum = 0;
    // 遍历题目列表 . 依次比对正确答案和我的答案
    foreach($subjects as $sub){
        if(!isset($ans_list[$sub['id']])){continue ;}
        $my_ans = trim($ans_list[$sub['id']],',');
        $true_ans = trim($sub['ques_result'],',');
        if(2 == $sub['ques_class']){
            // 多选把答案拆成数组之后拼回字符串进行比对
            $my_ans = explode(',',$my_ans);sort($my_ans);// 拆成数组后排序
            $my_ans = implode(',',$my_ans);// 拼回字符串
            $true_ans = explode(',',$true_ans);sort($true_ans);// 拆成数组后排序
            $true_ans = implode(',',$true_ans);// 拼回字符串
        }else{
            // 单选 + 判断
        }
        if($my_ans == $true_ans){$sorce_sum += $sub['ques_score'];}
    }
    return $sorce_sum;
}
/*
 * 生成成绩查询码
 * */
function getscore_code($p = "")
{
    return $p . date("ymdHis") . str_pad(getMillisecond() % 1000, 4, "0", STR_PAD_LEFT) . random(4);
}
/*
 * 获取优惠券类型*/
function type2typestr($type = 1){
    $arr = [
        1=>'满减',
        2=>'折扣',
        3=>'满减',
        4=>'折扣',
    ];
    return $arr[$type];
}
/*
 * 判断优惠券是否过期*/
function check_coupon_in_date($datetime){
    $end_timestamp = strtotime($datetime);
    return $end_timestamp > time();
}
/*
 * 获取VIP海报背景图URL地址*/
function get_vip_haibaobg(){
    $value = RotationImg::mk()->where(['where' => 2])->value('value');
    $list = is_null($value) ? [] : mb_unserialize($value);
    $pic = null;
    if(count($list)){
        $pic = $list[0];
    }
    return $pic;
}
/*
 * 添加日志*/
function add_log($type , $param){
    if('user_curr' == $type){
        $log = [
            'user_id'=>$param['user_id'],
            'curr_id'=>$param['curr_id'],
            'curr_child_id'=>$param['curr_child_id'],
            'datetime'=>$param['datetime'],
            'timestamp'=>$param['timestamp']
        ];
        LogUserCurrModel::mk()->insert($log);
    }
}

    if (!function_exists('trace_file')) {
        /**
         * 输出异常数据到文件
         * @param \Exception $exception
         * @return void
         */
        function trace_file(Exception $exception)
        {
            $path = app()->getRuntimePath() . 'trace';
            if (!file_exists($path)) mkdir($path, 0755, true);
            $name = substr($exception->getFile(), strlen(app()->getRootPath()));
            $file = $path . DIRECTORY_SEPARATOR . date('Ymd_His_') . strtr($name, ['/' => '.', '\\' => '.']);
            $class = get_class($exception);
            file_put_contents($file,
                "[CODE] {$exception->getCode()}" . PHP_EOL .
                "[INFO] {$exception->getMessage()}" . PHP_EOL .
                "[FILE] {$class} in {$name} line {$exception->getLine()}" . PHP_EOL .
                "[TIME] " . date('Y-m-d H:i:s') . PHP_EOL . PHP_EOL .
                '[TRACE]' . PHP_EOL . $exception->getTraceAsString()
            );
        }
    }

    if (!function_exists('sysdata')) {
        /**
         * JSON 数据读取与存储
         * @param string $name 数据名称
         * @param mixed $value 数据内容
         * @return mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\DbException
         * @throws \think\db\exception\ModelNotFoundException
         */
        function sysdata(string $name, $value = null)
        {
            if (is_null($value)) {
                return SystemService::instance()->getData($name);
            } else {
                return SystemService::instance()->setData($name, $value);
            }
        }
    }

    //参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
    function curl_request ( $url , $post = '' , $cookie = '' ,  $returnCookie = 0 ) {
        $curl  =  curl_init ( ) ;
        curl_setopt ( $curl , CURLOPT_URL ,  $url ) ;
        curl_setopt ( $curl , CURLOPT_USERAGENT ,  'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' ) ;
        curl_setopt ( $curl , CURLOPT_FOLLOWLOCATION ,  1 ) ;
        curl_setopt ( $curl , CURLOPT_AUTOREFERER ,  1 ) ;
        curl_setopt ( $curl , CURLOPT_REFERER ,  "http://XXX" ) ;
        if ( $post )  {
            curl_setopt ( $curl , CURLOPT_POST ,  1 ) ;
            curl_setopt ( $curl , CURLOPT_POSTFIELDS ,  $post ) ;
        }
        if ( $cookie )  {
            curl_setopt ( $curl , CURLOPT_COOKIE ,  $cookie ) ;
        }
        curl_setopt ( $curl , CURLOPT_HEADER ,  $returnCookie ) ;
        curl_setopt ( $curl , CURLOPT_TIMEOUT ,  10 ) ;
        curl_setopt ( $curl , CURLOPT_RETURNTRANSFER ,  1 ) ;
        $data  =  curl_exec ( $curl ) ;
        if  ( curl_errno ( $curl ) )  {
            return  curl_error ( $curl ) ;
        }
        curl_close ( $curl ) ;
        if ( $returnCookie ) {
            list ( $header ,  $body )  =  explode ( "\r\n\r\n" ,  $data ,  2 ) ;
            preg_match_all ( "/Set\-Cookie:([^;]*);/" ,  $header ,  $matches ) ;
            $info [ 'cookie' ]   =  substr ( $matches [ 1 ] [ 0 ] ,  1 ) ;
            $info [ 'content' ]  =  $body ;
            return  $info ;
        } else {
            //var_dump($data);die;
            return  $data ;
        }
    }

    //获取access_token并保存到token.txt文件中
    function build_access_token(){
        $ch = curl_init(); //初始化一个CURL对象
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb760ef897769ccfb&secret=254ca65098d0027b422c103670558ca2");//设置你所需要抓取的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置curl参数，要求结果是否输出到屏幕上，为true的时候是不返回到网页中,假设上面的0换成1的话，那么接下来的$data就需要echo一下。
        $data = json_decode(curl_exec($ch));
        //var_dump($data);die;
        if($data->access_token){
            //$token_file = fopen("token.txt","w") or die("Unable to open file!");//打开token.txt文件，没有会新建
            //fwrite($token_file,$data->access_token);//重写tken.txt全部内容
            //fclose($token_file);//关闭文件流
            return $data->access_token;
        }else{
            echo $data->errmsg;
        }
        curl_close($ch);
    }

    //发送消息  $fan = $this->sendfa($bao['name'],$bao['tel'],$user['openid']);
    function sendfa($data){
	    $access_token = build_access_token();
	    $datas = json_encode($data);
	    $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
	    //var_dump($datas);die;
	    $json = curl_request($url,$datas);
	    $students = json_decode($json,true);
	    //var_dump($students);die;
	    if($students['errcode'] == 0){
	        // return 1;
	    }else{
	        // return 2;
	    }
	}

    // 判断是否是手机端
    function isMobile(){
        //判断是否手机终端
        $useragent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $useragent_commentsblock = preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';

        $mobile_os_list = array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian'
                                ,'Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo'
                                ,'Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
        $mobile_token_list = array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240'
                                    ,'240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS'
                                    ,'PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ'
                                    ,'Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH'
                                    ,'Wapaka','DoCoMo','iPhone','iPod');
        $found_mobile = CheckSubstrs_($mobile_os_list,$useragent_commentsblock)||CheckSubstrs_($mobile_token_list,$useragent)
                      ||CheckSubstrs_($mobile_token_list,$useragent_commentsblock)||CheckSubstrs_($mobile_os_list,$useragent);
        if ($found_mobile){
            return true;
        }else{
            return false;
        }
    }

    function CheckSubstrs_($substrs,$text){
		foreach($substrs as $substr)
			if(false!==strpos($text,$substr)){
				return true;
			}
			return false;
	}

    function common_data()
    {
        // 存入session

        $company_info = CompanyInfo::mk()->order('id')->find();
        //友情链接
        $about_link = About_link::mk()->order('id')->select();
        $company_info['about_link'] = $about_link;
        //选择严重程度
        $severity = Severity::mk()->order('sort desc,id')->select();
        $company_info['severity'] = $severity;

        //选择维修项目
        $fix_items = FixItems::mk()->order('sort desc,id')->select();
        $company_info['fix_items'] = $fix_items;

        // $session = \Yii::$app->session;
		// if(isset($session["user_name"]) == false)
		// {//未登录,需要先登录805071
		// 	$url = Yii::$app->request->getUrl();
		// 	if(strpos($url, "login") == false)
		// 	{
		// 		$this->redirect('/site/login');
        //         header('Location: /site/login');
        //         exit;
		// 	}
		// }
        // Session::set("user_name","yangphp");
         $user_id = Session::get("user_id");
         if(isset($user_id) == false){
             $company_info['user_id'] = 0;
         }else{
             $company_info['user_id'] = $user_id;
             $username = Session::get("username");
             $company_info['username'] = $username;
         }
         //导航栏是否显示
	    $company_info['product'] = sysconf('nav.product');
        $company_info['solution'] = sysconf('nav.solution');
        $company_info['science'] = sysconf('nav.science');
        $company_info['information'] = sysconf('nav.information');
        $company_info['news'] = sysconf('nav.news');
        $company_info['contact'] = sysconf('nav.contact');
        $company_info['login'] = sysconf('nav.login');
        return $company_info;
    }
    
    function mb_unserialize($serial_str) {
        $out = preg_replace_callback( '!s:(\d+):"(.*?)";!s', function($r){ return 's:'.strlen($r[2]).':"'.$r[2].'";'; }, $serial_str );
        return unserialize($out);
    }

    //$type 0 获取微信URL-Link 1 获取URL-Scheme
	 function getwxlink($id,$type=0){
			$data = ShopOrder::mk()->where(['id'=>$id])->find();
			$status = $data['status'];
			$payment_status = $data['payment_status'];
			//待支付
			if ($status == '3' && $payment_status == '0'){
				if ($type == 1) {
					$data = [
						'jump_wxa' => ['path' => '/pages/order/index', 'query' => ''],
						'expire_type' => '1',
						'expire_interval' => '3',
					];
				}else{
					$data = [
						'path'=>'/pages/order/index',
						'expire_type'=>'1',
						'expire_interval'=>'3',
					];
				}
			}
			//待认证
			else if($status == '3' && $payment_status == '1'){
				if ($type == 1) {
					$data = [
						'jump_wxa' => ['path' => '/pages/material/pages/attest/index', 'query' => 'id=' . $id . '&base_type=0'],
						'expire_type' => '1',
						'expire_interval' => '3',
					];
				}else{
					$data = [
						'path'=>'/pages/material/pages/attest/index',
						"query"=> 'id=' . $id . '&base_type=0',
						'expire_type'=>'1',
						'expire_interval'=>'3',
					];
				}
			}
			//带视频
			else if($status == '4'){
				if ($type == 1) {
					$data = [
						'jump_wxa'=>['path'=>'/pages/forensics/pages/index/index','query'=>'record_id='.$id],
						'expire_type'=>'1',
						'expire_interval'=>'3',
					];
				}else {
					$data = [
						'path'=>'/pages/forensics/pages/index/index',
						"query"=> 'record_id='.$id,
						'expire_type'=>'1',
						'expire_interval'=>'3',
					];
				}
			}else{
				throw new Exception('状态错误');
			}

			$appid = sysconf('wechat.appid');
			$secret = sysconf('wechat.appsecret');
			$options = [
				'appid'=>$appid,
				'appsecret'=>$secret
			];
			$Scheme = new Scheme($options);
			// $data = [
			// 	'jump_wxa'=>['path'=>'/pages/order/index','query'=>''],
			// 	'expire_type'=>'1',
			// 	'expire_interval'=>'3',
			// ];

			if ($type == 1){
				$urlLink = $Scheme->create($data);
			}else{
				$urlLink = $Scheme->urlLink($data);
			}

			// array(3) {
			//   ["errcode"] => int(0)
			//   ["errmsg"] => string(2) "ok"
			//   ["openlink"] => string(35) "weixin://dl/business/?t=FVOWpHc9wfk"
			// }
			if($urlLink['errcode'] == '0'){
				if ($type == 1){
					$url_link = $urlLink['openlink'];
				}else{
					$url_link = $urlLink['url_link'];
				}
				return $url_link;
			}else{
				throw new Exception($urlLink['errmsg']);
			}
		}